<template>
  <transition name="slide-fade">
    <div v-if="isOpen" class="ai-assistant" :class="{ 'ai-assistant-open': isOpen }"
      :style="{ width: assistantWidth + 'px' }">
      <div class="ai-assistant-header">
        <h3>BigModel</h3>
        <button @click="close" class="close-button">×</button>
      </div>
      <div class="ai-assistant-content">
        <div class="chat-messages-wrapper">
          <div class="chat-messages custom-scrollbar" ref="chatMessagesRef">
            <transition-group name="message-fade">
              <div v-for="(message, index) in messages" :key="index" class="message-wrapper">
                <div :class="['message', message.role]">
                  <div v-if="message.role === 'assistant' && message.isStreaming">
                    <span class="streaming-text" v-html="formatMessage(message.content)"></span>
                  </div>
                  <div v-else v-html="formatMessage(message.content)"></div>
                </div>
              </div>
            </transition-group>
          </div>
        </div>
        <div class="chat-input">
          <input v-model="userInput" @keyup.enter="sendMessage" type="text" placeholder="输入消息..."
            :disabled="isLoading" />
          <button @click="sendMessage" class="send-button" :disabled="isLoading">
            {{ isLoading ? '发送中...' : '发送' }}
          </button>
        </div>
      </div>
      <div class="resize-handle" @mousedown="startResize"></div>
    </div>
  </transition>
</template>

<script setup>
import { ref, onMounted, nextTick, getCurrentInstance, watch } from 'vue';
import { marked } from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css'; // 使用更现代的样式

const { proxy } = getCurrentInstance();

const isOpen = ref(true);
const messages = ref([]);
const userInput = ref('');
const isLoading = ref(false);
const chatMessagesRef = ref(null);

const emit = defineEmits(['close']);

const close = () => {
  isOpen.value = false;
  setTimeout(() => {
    emit('close');
  }, 300);
};

const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
    }
  });
};

const sendMessage = async () => {
  if (userInput.value.trim() === '' || isLoading.value) return;

  const userMessage = { role: 'user', content: userInput.value };
  messages.value.push(userMessage);
  scrollToBottom();

  isLoading.value = true;
  const currentInput = userInput.value;
  userInput.value = '';

  try {
    const assistantMessage = { role: 'assistant', content: '', isStreaming: true };
    messages.value.push(assistantMessage);

    await proxy.$api.ai.streamMessage({
      model: "glm-4-flash", // 模型  这里不能改这里不能改这里不能改这里不能改这里不能改这里不能改这里不能改这里不能改这里不能改这里不能改这里不能改这里不能改
      messages: [
        { role: "system", content: "你是一个无敌小助手，你什么都会" },
        ...messages.value.filter(m => !m.isStreaming)
      ],
      stream: true,
    }, (chunk) => {
      try {
        const data = JSON.parse(chunk);
        if (data.choices && data.choices[0].delta && data.choices[0].delta.content) {
          const content = data.choices[0].delta.content;
          assistantMessage.content += content;
          // 强制更新视图
          messages.value = [...messages.value];
          scrollToBottom();
        }
        // 检查是否是最后一个块
        if (data.choices[0].finish_reason) {
          assistantMessage.isStreaming = false;
          // 再次更新视图
          messages.value = [...messages.value];
        }
      } catch (error) {
        console.error('Error parsing chunk:', error);
      }
    });

  } catch (error) {
    console.error('Error sending message:', error);
    messages.value.push({ role: 'assistant', content: '发生了一个错误。' });
  } finally {
    isLoading.value = false;
    scrollToBottom();
  }
};

const highlightCode = () => {
  nextTick(() => {
    document.querySelectorAll('pre code').forEach((block) => {
      hljs.highlightElement(block);
    });
  });
};

const formatMessage = (content) => {
  marked.setOptions({
    highlight: function (code, lang) {
      if (lang && hljs.getLanguage(lang)) {
        return hljs.highlight(code, { language: lang }).value;
      }
      return hljs.highlightAuto(code).value;
    },
    breaks: true,
    gfm: true
  });
  return marked(content);
};

watch(() => messages.value, () => {
  highlightCode();
}, { deep: true });

onMounted(() => {
  scrollToBottom();
  highlightCode();
});

const assistantWidth = ref(400); // 初始宽度
const minWidth = 300; // 最小宽度
const maxWidth = 800; // 最大宽度

const startResize = (e) => {
  e.preventDefault();
  window.addEventListener('mousemove', resize);
  window.addEventListener('mouseup', stopResize);
};

const resize = (e) => {
  const newWidth = window.innerWidth - e.clientX;
  const resultWidth = newWidth >= maxWidth ? 800 : newWidth <= minWidth ? 300 : newWidth
  assistantWidth.value = resultWidth;
};

const stopResize = () => {
  window.removeEventListener('mousemove', resize);
  window.removeEventListener('mouseup', stopResize);
};
</script>

<style scoped>
.ai-assistant {
  position: fixed;
  right: -400px;
  top: 50px;
  width: v-bind(assistantWidth + 'px');
  /* 使用动态宽度 */
  height: calc(100vh - 100px);
  background-color: var(--ai-assistant-bg);
  backdrop-filter: blur(10px);
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  /* transition: right 0.1s ease-in-out, opacity 0.1s ease-in-out, width 0.1s ease-in-out;  */
  display: flex;
  flex-direction: column;
  z-index: 1000;
  border-radius: 20px 0 0 20px;
  overflow: hidden;
  opacity: 0;
}

.ai-assistant-open {
  right: 0;
  opacity: 1;
}

.ai-assistant-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: var(--ai-assistant-header-bg);
  color: var(--ai-assistant-header-text);
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  color: var(--ai-assistant-header-text);
  cursor: pointer;
  transition: transform 0.3s ease;
}

.close-button:hover {
  transform: rotate(90deg);
}

.ai-assistant-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  height: calc(100% - 60px);
  /* 减去头部高度 */
  overflow: hidden;
  /* 防止内容溢出 */
}

.chat-messages-wrapper {
  flex: 1;
  overflow: hidden;
  border-radius: 15px;
  background-color: var(--ai-assistant-messages-bg);
  margin-bottom: 20px;
  padding-top: 10px;
  padding-bottom: 40px;
}

.chat-messages {
  height: 100%;
  overflow-y: auto;
  padding: 15px 15px 15px 20px;
  /* 增加左侧内边距 */
}

.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);
}

.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: var(--scrollbar-track);
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: var(--scrollbar-thumb);
  border-radius: 3px;
  border: 1px solid var(--ai-assistant-messages-bg);
  /* 减小边框宽度 */
}

.message {
  margin-bottom: 10px;
  padding: 0px 10px;
  border-radius: 10px;
  max-width: 80%;
  /* 限制消息宽度，使其不会占满整行 */
  animation: message-pop 0.3s ease-out;
  color: var(--ai-assistant-text);
  word-wrap: break-word;
  overflow-wrap: break-word;
  overflow-x: hidden;
}

@keyframes message-pop {
  0% {
    transform: scale(0.8);
    opacity: 0;
  }

  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.message.user {
  background-color: var(--user-message-bg);
  color: var(--user-message-text);
  align-self: flex-end;
  /* 将用户消息靠右对齐 */
  margin-left: auto;
  /* 将用户消息推到右侧 */
  margin-right: 0;
  /* 确保右侧没有边距 */
}

.message.assistant {
  background-color: var(--ai-message-bg);
  color: var(--ai-message-text);
  align-self: flex-start;
  /* 保持AI消息靠左对齐 */
  margin-right: auto;
  /* 将AI消息推到左侧 */
  margin-left: 0;
  /* 确保左侧没有边距 */
}

/* 添加新的样式来包装消息 */
.message-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.streaming-text {
  display: inline;
}


@keyframes blink {
  0% {
    opacity: 0;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}

.chat-input {
  display: flex;
  background: var(--ai-assistant-input-bg);
  border-radius: 20px;
  overflow: hidden;
  padding: 5px;
  transition: box-shadow 0.3s ease;
  margin-top: auto;
  /* 将输入框推到底部 */
}

.chat-input:focus-within {
  box-shadow: 0 0 10px rgba(var(--thisBackgroundRGB), 0.3);
}

.chat-input input {
  flex: 1;
  padding: 10px 15px;
  border: none;
  background: transparent;
  color: var(--ai-assistant-input-text);
  font-size: 14px;
  transition: all 0.3s ease;
}

.chat-input input:focus {
  outline: none;
}

.send-button {
  padding: 10px 20px;
  background: var(--ai-assistant-button-gradient);
  color: var(--ai-assistant-button-text);
  border: none;
  border-radius: 15px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease, transform 0.1s ease;
}

.send-button:hover {
  opacity: 0.9;
  transform: scale(1.05);
}

.send-button:active {
  transform: scale(0.95);
}

.send-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(400px);
  opacity: 0;
}

.message-fade-enter-active,
.message-fade-leave-active {
  transition: all 0.5s ease;
}

.message-fade-enter-from,
.message-fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

.char-animate {
  display: inline-block;
  opacity: 0;
  transform: translateY(10px);
  animation: fadeInUp 0.3s forwards;
  /* font-weight: bold; */
  white-space: pre-wrap;
  font-size: 13px;
}

@keyframes fadeInUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.streaming-text .char-animate {
  animation-duration: 0.1s;
}

.char-animate:nth-child(1) {
  animation-delay: 0.01s;
}

.char-animate:nth-child(2) {
  animation-delay: 0.02s;
}

.char-animate:nth-child(3) {
  animation-delay: 0.03s;
}

.char-animate:nth-child(4) {
  animation-delay: 0.04s;
}

.char-animate:nth-child(5) {
  animation-delay: 0.05s;
}

:deep(pre) {
  background-color: #282c34;
  border-radius: 8px;
  padding: 16px;
  overflow-x: auto;
  /* 保持水平滚动 */
  margin: 10px 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-width: 100%;
  /* 确保不会超出父容器 */
  white-space: pre;
  /* 保持代码的格式 */
}

:deep(code) {
  font-family: 'Fira Code', 'Consolas', 'Monaco', 'Andale Mono', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  display: inline-block;
  /* 使代码块保持在一行 */
  min-width: 100%;
  /* 确保代码块至少和父容器一样宽 */
}

/* 改进滚动条样式 */
:deep(pre)::-webkit-scrollbar {
  width: 8px;
  height: 8px;
  /* 确保水平滚动条高度足够 */
  background-color: #282c34;
  /* 滚动条背景颜色 */
}

:deep(pre)::-webkit-scrollbar-thumb {
  background-color: #61afef;
  /* 滚动条滑块颜色，改为亮蓝色 */
  border-radius: 4px;
}

:deep(pre)::-webkit-scrollbar-track {
  background-color: #3e4451;
  /* 滚动条轨道颜色，稍微亮一点 */
}

/* 添加语言标签 */
:deep(pre) {
  position: relative;
}

:deep(pre)::before {
  content: attr(data-language);
  position: absolute;
  top: 0;
  right: 10px;
  font-size: 12px;
  color: #abb2bf;
  background-color: #3e4451;
  padding: 2px 6px;
  border-radius: 0 0 4px 4px;
}


.resize-handle {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 7px;
  opacity: 0;
  cursor: ew-resize;
}

/* 确保内容适应新宽度 */
.ai-assistant-content,
.chat-messages-wrapper,
.chat-messages,
.chat-input {
  width: 100%;
  box-sizing: border-box;
}

/* 调整消息最大宽度为百分比 */
.message {
  max-width: 90%;
}
</style>